package com.nf.health.app.bodyfat;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.android.volley.VolleyError;
import com.nf.health.app.AfinalDb.MeasureDataDao;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.activity.global.RegisterNickActivity;
import com.nf.health.app.activity.my.MyShopStoreActivity;
import com.nf.health.app.adapter.OnMyClickListener;
import com.nf.health.app.customview.MenuPopupWindow;
import com.nf.health.app.customview.WheelView;
import com.nf.health.app.bodyfat.bean.BodyFatInfo;
import com.nf.health.app.models.DeviceData;
import com.nf.health.app.models.UserInfo;
import com.nf.health.app.service.BluetoothLeService;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.ViewUtil;
import com.nf1000.balancelibrary.BluetoolUtil;
import com.nf1000.balancelibrary.BluetoothTools;
import com.nf1000.balancelibrary.PollingUtils;
import com.nf1000.balancelibrary.ScaneBluetoothService;
import com.nf1000.balancelibrary.StringUtils;
import com.nf1000.balancelibrary.TimeService;
import com.nf1000.balancelibrary.newbalance.ActionConstant;
import com.nf1000.balancelibrary.newbalance.BleUuid;
import com.nf1000.balancelibrary.newbalance.LefuBluetoothController;
import com.nf1000.balancelibrary.newbalance.ParseUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bluetools.ProtocolParser;

/**
 * Created by hepan on 2016/3/18.
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class BodyFatDataNewActivity extends BaseActivity {

    private static final long INTERVAL_TIME = 5 * 1000;
    private static final String TAG = BodyFatDataNewActivity.class.getSimpleName();
    private static final String FLAG_ADD_BALANCE = "flagAddBalance";
    private static final String FLAG_ADD_BALANCE_CACHE = "flagAddBalanceCache";
    private static final String FLAG_ADD_BALANCE_MANUALLY = "flag_add_balance_manually";
    boolean isLoading = false;
    /**
     * 体脂选择范围,体脂选择值
     */
    private String[] weight_range = new String[80];
    private String weight_chosen = "60"; //默认60kg

    @Bind(R.id.tv_weight)
    TextView tvWeight;
    @Bind(R.id.tv_history_data)
    TextView tvHistoryData;
    @Bind(R.id.tv_zfl)
    TextView tvZfl;
    @Bind(R.id.tv_gg)
    TextView tvGg;
    @Bind(R.id.tv_jrl)
    TextView tvJrl;
    @Bind(R.id.tv_pxzf)
    TextView tvPxzf;
    @Bind(R.id.tv_shl)
    TextView tvShl;
    @Bind(R.id.tv_jcdx)
    TextView tvJcdx;
    @Bind(R.id.btn_measure)
    Button btnMeasure;
    @Bind(R.id.titlebar_right_view)
    ImageView titlebarRightView;

    //体脂数据bean类
    BodyFatInfo bodyfatinfo;
    // Device scan callback.
    private BluetoothAdapter.LeScanCallback mLeScanCallback;
    //    private BluetoothAdapter mBluetoothAdapter;
    // 蓝牙服务类
    private BluetoothLeService mBluetoothLeService;
    private List<BluetoothDevice> devices = new ArrayList<>();
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case ActionConstant.ACTION_DATA_AVAILABLE: {
                    System.out.println("收到脂肪称报告数据");
                    byte[] value = (byte[]) msg.obj;
                    final String result = ParseUtil.getResult(value);
                    String[] rec = null;

                    mDevice = null;
                    if (!result.startsWith("fd33") && result.length() >= 32) {
                        rec = ParseUtil.parse(result);
                    }
//                    showResult(rec);
//                    handleBalanceResult(value);
                    break;
                }
                case ActionConstant.ACTION_START_SCAN: {
                    System.out.println("开始扫描设备");
                    break;
                }
                default:
                    break;
            }
            return false;
        }
    });
    private ServiceConnection mServiceConnection;
    private String deviceType;
    String deviveName;
    private boolean isSuccess;
    protected static final UUID CHARACTERISTIC_UPDATE_NOTIFICATION_DESCRIPTOR_UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
    /**
     * 新的体脂秤
     */
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothAdapter mBTAdapter;
    private BluetoothDevice mDevice;
    private BluetoothGatt mConnGatt;
    private BluetoothGattCharacteristic writeCharacter = null;
    private LefuBluetoothController mBluetoothController;
    //缓存数据
    private List<BodyFatInfo> cacheInfos;
    private int upload_cache_index = 0;//记录当前上传数据位置

    private String deviceResponse;
    /*Gatt回调*/
    private BluetoothGattCallback mGattcallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                System.out.println("设备连接成功" + System.currentTimeMillis());
                mConnGatt.connect();
                //搜索支持的 服务
                mConnGatt.discoverServices();
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                System.out.println("设备断开连接");
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            for (BluetoothGattService service : gatt.getServices()) {
                if ((service == null) || (service.getUuid() == null)) {
                    continue;
                }
                if (BleUuid.SERVICE_WRITE_STRING.equalsIgnoreCase(service.getUuid().toString())) {
                    writeCharacter = service.getCharacteristic(UUID.fromString(BleUuid.CHAR_WRITE_STRING));
                    /*发送模拟用户数据*/
//                    writeCharacter.setValue(new byte[]{(byte) 0xFE, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0xAF, (byte) 0x19, (byte) 0x01, (byte) 0xB6});
                    writeCharacter.setValue(getInitByte());
                    if (mConnGatt.writeCharacteristic(writeCharacter)) {
                        System.out.println("数据发送成功");
                    }
                }
            }
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            System.out.println("读取数据");
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            System.out.println("写入数据");
            setCharacteristicNotification(mDevice, UUID.fromString(BleUuid.SERVICE_WRITE_STRING), UUID.fromString(BleUuid.CHAR_READ_STRING), true);
        }


        @SuppressLint("NewApi")
        @Override
        public void onCharacteristicChanged(android.bluetooth.BluetoothGatt gatt, android.bluetooth.BluetoothGattCharacteristic characteristic) {
            if (BleUuid.CHAR_READ_STRING.equalsIgnoreCase(characteristic.getUuid().toString())) {
                final byte[] value = characteristic.getValue();
                StringBuilder response = new StringBuilder("");
                for (int i = 0; i < value.length; i++) {
                    int v = value[i] & 0xFF;
                    String hv = Integer.toHexString(v);
                    if (hv.length() < 2) {
                        response.append(0);
                    }
                    response.append(hv);
                }

                deviceResponse = response.toString();
                System.out.println("终端回复数据:" + deviceResponse);
                if ("fd31000000000031".equals(deviceResponse)) {
//                    writeCharacter.setValue(new byte[]{(byte) 0xFE, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0xAF, (byte) 0x19, (byte) 0x01, (byte) 0xB6});
                    writeCharacter.setValue(getInitByte());
                    if (mConnGatt.writeCharacteristic(writeCharacter)) {
                        System.out.println("重新写入数据发送成功");
                    }
                } else if ("fd31000000000033".equals(deviceResponse)) {
                    Toast.makeText(BodyFatDataNewActivity.this, "脂肪错误", Toast.LENGTH_LONG).show();
                } else {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            try {
                                String[] result = ParseUtil.parse(deviceResponse);
                                if (!isLoading) {
                                    handleBalanceResult(value);
                                    isLoading = true;
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        ;
                    });
                }
            }
        }
    };

    /**
     * 设置收到数据提醒
     */
    @SuppressLint("NewApi")
    public boolean setCharacteristicNotification(BluetoothDevice device, UUID serviceUuid, UUID characteristicUuid, boolean enable) {
        BluetoothGattCharacteristic characteristic = mConnGatt.getService(serviceUuid).getCharacteristic(characteristicUuid);
        mConnGatt.setCharacteristicNotification(characteristic, enable);
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CHARACTERISTIC_UPDATE_NOTIFICATION_DESCRIPTOR_UUID);
        descriptor.setValue(enable ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE : new byte[]{0x00, 0x00});
        return mConnGatt.writeDescriptor(descriptor); // descriptor write
    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothTools.ACTION_START_DISCOVERY.equals(action)) {
                LogUtil.i(TAG, "开始扫描");
            } else if (BluetoothTools.ACTION_NOT_FOUND_SERVER.equals(action)) {
                LogUtil.i(TAG, "没有连接到设备");
            } else if (BluetoothTools.ACTION_FOUND_DEVICE.equals(action)) {
                if (null != BluetoolUtil.lastDevice) {
                    //String address = BluetoolUtil.lastDevice.getAddress();
                    String name = BluetoolUtil.lastDevice.getName();
                    LogUtil.i(TAG, "发现设备" + name);
                }

            } else if (BluetoothTools.ACTION_CONNECT_SUCCESS.equals(action)) {
                if (null != BluetoolUtil.lastDevice) {
                    //String address = BluetoolUtil.lastDevice.getAddress();
                    String name = BluetoolUtil.lastDevice.getName();
                    LogUtil.i(TAG, "连接成功：" + name);
                }

            } else if (BluetoothTools.ACTION_DATA_TO_GAME.equals(action)) {
                if (null != BluetoolUtil.lastDevice) {
                    String name = BluetoolUtil.lastDevice.getName();
                    LogUtil.i(TAG, "ACTION_DATA_TO_GAME" + name);
                }

            } else if (BluetoothTools.ACTION_CONNECT_ERROR.equals(action)) {
                if (null != BluetoolUtil.lastDevice) {
                    //String address = BluetoolUtil.lastDevice.getAddress();
                    String name = BluetoolUtil.lastDevice.getName();
                    LogUtil.i(TAG, "连接失败" + name);
                    if (!isSuccess) {
                        hideLoading();
                        showToast("测量失败，请重试");
                    }
                }

            } else if (BluetoothTools.ACTION_READ_DATA.equals(action)) {
                byte[] data = intent.getByteArrayExtra("readMessage");
                LogUtil.i(TAG, "数据" + StringUtils.bytes2HexString(data));
                if (!isLoading) {
                    handleBalanceResult(data);
                    isLoading = true;
                }
                isSuccess = true;
                PollingUtils.stopPollingService(BodyFatDataNewActivity.this, ScaneBluetoothService.class, ScaneBluetoothService.ACTION);
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContent(R.layout.activity_body_fat_date);
        setTitleBar(R.layout.layout_common_header);
        ButterKnife.bind(this);
        deviceType = getIntent().getStringExtra("deviceType");

        initView();
        initListener();

        initBluetooth();

        init();

        //检测是否完善注册信息
        boolean registerInfoCompleted = PreferenceHelper.getBoolean(PreferenceHelper.REGISTER_INFO_COMPLETE, false);
        if (!registerInfoCompleted) {
            showToast("请完善注册信息");
            finish();
            Bundle bundle = new Bundle();
            bundle.putString("type", "123");//跟注册时一样的type
            ActivityUtils.showActivity(this, RegisterNickActivity.class, bundle);
        }

        //检测是否有为上传的缓存数据
        checkCacheData();
    }

    //检测是否有未上传的缓存数据
    private void checkCacheData() {
        cacheInfos = MeasureDataDao.getAllBodyFat();
        if (cacheInfos.size() > 0) {
            uploadCacheData(0);
        }
    }

    //上传缓存数据,一条一条上传
    private void uploadCacheData(int index) {
        if (cacheInfos.size() <= index) {
            return;
        }
        upload_cache_index = index;
        BodyFatInfo info = cacheInfos.get(index);
        provider.requestAddDeviceBalance(info.getWeight(),
                "", info.getFat(),
                info.getBone(), info.getJiRou(),
                info.getPiXiaZhiFang(), info.getShuiFen(),
                info.getbMR(), "",
                "2",
                FLAG_ADD_BALANCE_CACHE);
    }


    private void init() {
        String sex = "01";
        int height = 170;
        int age = 30;
        try {
            UserInfo userInfo = PreferenceHelper.getUser();
            double heightD = Double.parseDouble(userInfo.getHeight());
            height = (int) heightD;
            sex = userInfo.getSex().equals("1") ? "01" : "00";
            String currentYear = userInfo.getBirthday().split("-")[0];
            age = Calendar.getInstance().get(Calendar.YEAR) - Integer.parseInt(currentYear);
            height = height > 160 ? height : 170;
        } catch (Exception e) {

        }
        // 开启后台service
        // 开启扫描
        Intent serviceIntent = new Intent(this, TimeService.class);
        serviceIntent.putExtra("sex", sex);
        serviceIntent.putExtra("height", height);
        serviceIntent.putExtra("age", age);
        startService(serviceIntent);

        // 注册BoradcasrReceiver
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothTools.ACTION_NOT_FOUND_SERVER);
        intentFilter.addAction(BluetoothTools.ACTION_FOUND_DEVICE);
        intentFilter.addAction(BluetoothTools.ACTION_DATA_TO_GAME);
        intentFilter.addAction(BluetoothTools.ACTION_CONNECT_SUCCESS);
        intentFilter.addAction(BluetoothTools.ACTION_CONNECT_ERROR);
        intentFilter.addAction(BluetoothTools.ACTION_READ_DATA);
        registerReceiver(broadcastReceiver, intentFilter);
    }

    private void initBluetooth() {
        mBluetoothController = LefuBluetoothController.getInstance(this, mHandler);
        mBTAdapter = BluetoothAdapter.getDefaultAdapter();
        // 检查当前手机是否支持blue 蓝牙,如果不支持退出程序
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            showToast("不支持蓝牙4.0通讯");
            finish();
            return;
        }

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // 检查设备上是否支持蓝牙
        if (mBluetoothAdapter == null) {
            showToast("没有发现蓝牙模块");
            return;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
                @Override
                public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (device != null) {
                                if (!TextUtils.isEmpty(device.getName())) {
                                    if (device.getName().toLowerCase().contains("scale")) {
                                        if (!devices.contains(device)) {
                                            devices.add(device);
                                        }
                                    }
                                }
                            }
                            /*if (device != null && device.getName().contains(BluetoothDeviceAttr.BLOOD_PRESSURE_DEVICE_NAME)) {
                                if (!devices.contains(device)) {
                                    devices.add(device);
                                }
                            }*/
                        }
                    });
                }
            };
        } else {
            showToast("设备蓝牙版本过低");
            finish();
            return;
        }
        bindLeService();
        if (!mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.enable();
        }

        mBluetoothController.initBle();
    }

    private void bindLeService() {
        mServiceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName,
                                           IBinder service) {
                mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
                if (!mBluetoothLeService.initialize()) {
                    new MaterialDialog.Builder(BodyFatDataNewActivity.this)
                            .title("提示")
                            .content("蓝牙初始化服务失败了~")
                            .positiveText("确定")
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(MaterialDialog dialog, DialogAction which) {
                                    finish();
                                }
                            })
                            .show();
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                mBluetoothLeService = null;
            }
        };

        Intent bleService = new Intent(this, BluetoothLeService.class);
        bleService.putExtra("type", DeviceData.Type.BLOOD_PRESSURE);
        bindService(bleService, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    /**
     * 初始化监听器
     */
    private void initListener() {
        titlebarRightView.setOnClickListener(this);
        btnMeasure.setOnClickListener(this);
        tvHistoryData.setOnClickListener(this);
    }

    /**
     * 初始化view
     */
    private void initView() {
        //设置标题
        ViewUtil.setText(this, R.id.titlebar_title_tv, "体脂秤数据");
        titlebarRightView.setVisibility(View.VISIBLE);
        ViewUtil.setImageResoure(this, R.id.titlebar_right_view, R.drawable.ic_title_setting);

        //展示最后一次测量结果
        showLatestMeasuredData();

    }

    private void showLatestMeasuredData() {
        BodyFatInfo info = PreferenceHelper.getBodyFatInfo();
        if (info != null) {
            tvWeight.setText(info.getWeight());
            tvZfl.setText(info.getFat());
            tvShl.setText(info.getShuiFen());
            tvPxzf.setText(info.getPiXiaZhiFang());
            tvJrl.setText(info.getJiRou());
            tvGg.setText(info.getBone());
            tvJcdx.setText(info.getbMR());
        }
        String weight = PreferenceHelper.getString(PreferenceHelper.BODY_FAT_LATEST_DATA, "");
        tvWeight.setText(weight);
        System.out.println("");
    }

    /**
     * 初始化绑定设备弹窗
     */
    private void initPop() {
        String address = PreferenceHelper.getString(PreferenceHelper.BALANCE_ADDRESS, "");
        if (!"".equals(address)) {
            deviveName = "体脂秤:" + address;
        }
        MenuPopupWindow pop = new MenuPopupWindow(this, deviveName);
        pop.showAsDropDown(titlebarRightView);
        pop.setOnMenuItemClickListener(new OnMyClickListener() {
            @Override
            public void onClick(int position, String flag) {
                if (R.id.ll_bind_device == position) {
                    if (PreferenceHelper.getBoolean(PreferenceHelper.BALANCE_IS_BING, false)) {
                        //TODO 解绑操作
                        PreferenceHelper.putBoolean(PreferenceHelper.BALANCE_IS_BING, false);
                        PreferenceHelper.putString(PreferenceHelper.BALANCE_ADDRESS, "");
                        PreferenceHelper.putString(PreferenceHelper.BALANCE_NAME, "");
                        hideLoading();
                        showToast("解绑成功");
                        deviveName = "";
                        mBluetoothLeService.close();
                    } else {
                        scanLeDevice(true);
                    }
                } else if (R.id.tv_manual_input == position) {
                    //手动添加数据
                    manuallyAddDada();
                } else if (R.id.tv_loadl_input == position) {
                    ActivityUtils.showActivity(BodyFatDataNewActivity.this, MyShopStoreActivity.class);
                }
            }
        });
    }

    /**
     * 手动添加数据
     */
    private void manuallyAddDada() {
        for (int i = 0; i < 80; i++) {
            weight_range[i] = i + 20 + "";
        }
        weight_chosen = "60"; //默认60kg
        View outerView = LayoutInflater.from(this).inflate(R.layout.wheel_view_body_fat, null);
        WheelView wv = (WheelView) outerView.findViewById(R.id.wheel_view_wv);
        wv.setOffset(1);
        wv.setItems(Arrays.asList(weight_range));
        wv.setSeletion((int) weight_range.length / 2);
        wv.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                weight_chosen = item;
            }
        });

        new AlertDialog.Builder(this)
                .setTitle("请选择体重值")
                .setView(outerView)
                .setNegativeButton("取消", null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        provider.requestAddDeviceBalance(weight_chosen,
                                "0", "0",
                                "0", "0",
                                "0", "0",
                                "0", "0",
                                "1",
                                FLAG_ADD_BALANCE_MANUALLY);

                        bodyfatinfo = new BodyFatInfo();
                        bodyfatinfo.setAge(PreferenceHelper.getBodyFatInfo().getAge());
                        bodyfatinfo.setHeight(PreferenceHelper.getBodyFatInfo().getHeight());
                        bodyfatinfo.setWeight(weight_chosen + "");
                        bodyfatinfo.setFat(PreferenceHelper.getBodyFatInfo().getFat());
                        bodyfatinfo.setBone(PreferenceHelper.getBodyFatInfo().getBone());
                        bodyfatinfo.setJiRou(PreferenceHelper.getBodyFatInfo().getJiRou());
                        bodyfatinfo.setPiXiaZhiFang(PreferenceHelper.getBodyFatInfo().getPiXiaZhiFang());
                        bodyfatinfo.setShuiFen(PreferenceHelper.getBodyFatInfo().getShuiFen());
                        bodyfatinfo.setbMR(PreferenceHelper.getBodyFatInfo().getbMR());
                        PreferenceHelper.putBodyFatInfo(bodyfatinfo);
                        tvWeight.setText(weight_chosen + "");
                        PreferenceHelper.putString(PreferenceHelper.BODY_FAT_LATEST_DATA, weight_chosen + "");
                    }
                })
                .show();
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        if (FLAG_ADD_BALANCE_MANUALLY.equals(actionName)) {
            showToast("手动上传成功");
            provider.requestAddScore("14", "");//添加积分
        } else if (FLAG_ADD_BALANCE.equals(actionName)) {
            isLoading = false;
            hideLoading();
            showToast("数据已上传到云端");
            provider.requestAddScore("14", "");//添加积分
            ActivityUtils.showActivity(this, BodyFatMeasuredResultActivity.class);
        } else if (FLAG_ADD_BALANCE_CACHE.equals(actionName)) {
            //清空对应数据
            MeasureDataDao.deleteBodyFatById(cacheInfos.get(upload_cache_index).getId());
            uploadCacheData(++upload_cache_index);
        }
    }

    @Override
    public void handleActionError(String actionName, String response, VolleyError error) {
        super.handleActionError(actionName, response, error);
        if (FLAG_ADD_BALANCE_MANUALLY.equals(actionName) || FLAG_ADD_BALANCE.equals(actionName)) {
            MeasureDataDao.saveBodyFatBean(bodyfatinfo);
        }
    }

    private void scanLeDevice(final boolean enable) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            if (enable) {
                showLoading("查找设备中..");
                devices.clear();
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
                // Stops scanning after a pre-defined scan period.
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                            mBluetoothAdapter.stopLeScan(mLeScanCallback);
                            hideLoading();
                            showBluetoothNames();
                        }
                    }
                }, INTERVAL_TIME);
                mBluetoothAdapter.startLeScan(mLeScanCallback);
            } else {
                try {
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                } catch (Exception e) {
                }
            }
        }
    }

    private void showBluetoothNames() {
        if (devices.size() <= 0) {
            new MaterialDialog.Builder(this).title("提示").content("没有发现体脂秤噢~").positiveText("确定").show();
            return;
        }
        String[] deviceNames = new String[devices.size()];
        for (int i = 0; i < devices.size(); i++) {
            String address = devices.get(i).getAddress();
            deviceNames[i] = "体脂秤-" + address.replace(":", "");
        }
        //mLeScanCallback 将搜索结果添加到集合中
        if(!isFinishing()) {
            new MaterialDialog.Builder(this)
                    .title("体脂秤")
                    .items(deviceNames)
                    .itemsCallback(new MaterialDialog.ListCallback() {
                        @Override
                        public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                            PreferenceHelper.putBoolean(PreferenceHelper.BALANCE_IS_BING, true);
                            PreferenceHelper.putString(PreferenceHelper.BALANCE_NAME, "体脂秤-" + devices.get(which).getAddress().replace(":", ""));
                            mDevice = devices.get(which);//把扫描的设备保存起来
                            PreferenceHelper.putString(PreferenceHelper.BALANCE_ADDRESS, devices.get(which).getAddress());
                            deviveName = "体脂秤-" + devices.get(which).getAddress().replace(":", "");
                            dialog.dismiss();
                        }
                    })
                    .show();
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            //右边按钮的点击事件
            case R.id.titlebar_right_view:
                initPop();
                break;
            case R.id.btn_measure:
                //如果没有绑定设备，则先进行搜索
                if (PreferenceHelper.getBoolean(PreferenceHelper.BALANCE_IS_BING, false)) {
                    showLoading("测量中...");
                    /*判断是否搜索到蓝牙设备*/
                    if (mDevice != null) {
                        mBluetoothController.connectBluetoothDevice(mDevice);
                        final BluetoothDevice device1 = mBTAdapter.getRemoteDevice(mDevice.getAddress());
                        mConnGatt = device1.connectGatt(BodyFatDataNewActivity.this, true, mGattcallback);
                    }
                    SystemClock.sleep(500);
                    PollingUtils.startPollingService(this, 10, ScaneBluetoothService.class, ScaneBluetoothService.ACTION);//循环扫描
                } else {
                    initPop();
                }
                break;
            //体脂历史数据
            case R.id.tv_history_data:
                ActivityUtils.showActivity(this, BodyFatHistoryDataActivity.class);
                break;
        }
    }

    /**
     * 处理体脂数据
     *
     * @param data
     */
    private void handleBalanceResult(byte[] data) {
        //停止扫描
        PollingUtils.stopPollingService(BodyFatDataNewActivity.this, ScaneBluetoothService.class, ScaneBluetoothService.ACTION);

        String msg = ProtocolParser.bytes2HexString(data);
        int age = Integer.parseInt(msg.substring(4, 6), 16) & 127;
        int height = Integer.parseInt(msg.substring(6, 8), 16);//CM
        int weightTemp = Integer.parseInt(msg.substring(8, 12), 16);//weightTemp*0.1KG
        float weight = (float) (Math.floor(weightTemp * 0.1f * 10) / 10);//保留一位小数
        float fat = Integer.parseInt(msg.substring(12, 16), 16) * 0.1f;//脂肪率 *0.1%
        fat = Math.round(fat * 10) / 10;
        float boneTemp = Integer.parseInt(msg.substring(16, 18), 16);
        float v = (boneTemp * 0.1f) / (weightTemp * 0.1f) * 100.0f;//骨骼率
        float bone = (float) (Math.floor(v * 10) / 10);//保留一位小数
        bone = bone * weight * 0.01f;//改为以骨骼含量(kg)上传,2016-07-12
        bone = (float) (Math.floor(bone * 10) / 10);
        float jiRou = Integer.parseInt(msg.substring(18, 22), 16) * 0.1f;//肌肉含量率 *0.1%
        jiRou = Math.round(jiRou * 10) / 10;
        int piXiaZhiFang = Integer.parseInt(msg.substring(22, 24), 16);//内脏脂肪等级
        float shuiFen = Integer.parseInt(msg.substring(24, 28), 16) * 0.1f;//水分含量率 *0.1%
        shuiFen = Math.round(shuiFen * 10) / 10;
        float bMR = Integer.parseInt(msg.substring(28, 32), 16) * 1.0f;//热量含量
        bMR = Math.round(bMR * 10) / 10;

        //TODO  适配数据，修改布局
        hideLoading();

        tvGg.setText(bone + "");
        tvZfl.setText(fat + "");
        tvJrl.setText(jiRou + "");
        tvPxzf.setText(piXiaZhiFang + "");
        tvShl.setText(shuiFen + "");
        tvJcdx.setText(bMR + "");
        tvWeight.setText(weight + "");

        provider.requestAddDeviceBalance(String.valueOf(weight),
                "", String.valueOf(fat),
                String.valueOf(bone), String.valueOf(jiRou),
                String.valueOf(piXiaZhiFang), String.valueOf(shuiFen),
                String.valueOf(bMR), "",
                "2",
                FLAG_ADD_BALANCE);
        /**
         * 存储体脂测量数据信息并展示结果
         */
        bodyfatinfo = new BodyFatInfo();
        bodyfatinfo.setAge(age + "");
        bodyfatinfo.setHeight(height + "");
        bodyfatinfo.setWeight(weight + "");
        bodyfatinfo.setFat(fat + "");
        bodyfatinfo.setBone(bone + "");
        bodyfatinfo.setJiRou(jiRou + "");
        bodyfatinfo.setPiXiaZhiFang(piXiaZhiFang + "");
        bodyfatinfo.setShuiFen(shuiFen + "");
        bodyfatinfo.setbMR(bMR + "");
        PreferenceHelper.putBodyFatInfo(bodyfatinfo);
        PreferenceHelper.putString(PreferenceHelper.BODY_FAT_LATEST_DATA, weight + "");
        /*上传成功后断开连接*/
        if (mDevice != null) {
            if (mConnGatt != null) {
                mConnGatt.disconnect();
                mConnGatt = null;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (broadcastReceiver != null) {
            unregisterReceiver(broadcastReceiver);
        }
        if (mServiceConnection != null) {
            unbindService(mServiceConnection);
        }
        stopService(new Intent(this, TimeService.class));
        PollingUtils.stopPollingService(this, ScaneBluetoothService.class, ScaneBluetoothService.ACTION);
        mBluetoothLeService.close();
        mBluetoothLeService = null;

        /*解绑设备*/
        if (mDevice != null) {
            if (mConnGatt != null) {
                mConnGatt.disconnect();
                mConnGatt = null;
            }
        }
    }

    /*显示结果*/
    void showResult(String[] result) {
        if (result == null || result.length < 0) {
            System.out.println("无数据");
        } else {
            new AlertDialog.Builder(this).setTitle("信息").setItems(result, null).setNegativeButton("确认", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    arg0.dismiss();
                }
            }).show();
        }
    }

    public byte[] getInitByte() {
//        writeCharacter.setValue(new byte[]{(byte) 0xFE, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0xAF, (byte) 0x19, (byte) 0x01, (byte) 0xB6});
        byte[] bytes = new byte[8];
        bytes[0] = (byte) 0xfe; // 1 FE 包头
        bytes[1] = 0x01; // 2 03 用户组号
        //性别
        if (PreferenceHelper.getString(PreferenceHelper.USERSEX, "0").equals("0")) {
            bytes[2] = 0x00;
        } else {
            bytes[2] = 0x01;
        }
        bytes[3] = 0x00; //4 02 运动员级别 0普通 1业余 2专业

        //身高
        double heightD = Double.valueOf(PreferenceHelper.getString(PreferenceHelper.USERHEIGHT, "175"));
        int height = (int) heightD;
        bytes[4] = height <= 0 ? (byte) 0xaf : (byte) height;//身高

        //年龄
        String birthday = PreferenceHelper.getString(PreferenceHelper.BIRTHDAY, "1990");
        int age;
        if (!TextUtils.isEmpty(birthday)) {
            age = Calendar.getInstance().get(Calendar.YEAR) - Integer.valueOf(birthday.substring(0, 4));
            if (age == 0) {
                age = 1;
            }
        } else {
            age = 25;
        }
        bytes[5] = (byte) age; // 6 19 年龄

        bytes[6] = 0x01; // 01单位 01千克 02lb(英石) 03ST:LB(英磅)
        bytes[7] = (byte) (bytes[1] ^ bytes[2] ^ bytes[3] ^ bytes[4] ^ bytes[5] ^ bytes[6]);
        return bytes;
    }

}
